#!/usr/bin/env groovy

def registry = "172.17.8.51"
def project = "test"
def app_name = "tomcat-java-demo"
def image_name = "${registry}/${project}/${app_name}:${BUILD_NUMBER}"
def git_address = "http://172.17.8.53:9999/test/tomcat-java-demo.git"
def docker_registry_auth = "ed472212-785d-4474-8a90-5b0ed8ccdc84"
def git_auth = "c38d36a2-1c23-41b9-825d-7a4156593c18"

# docker_registry_auth和git_auth为jenkins的Credentials中的ID
# 添加方式为：以"Username with password"方式，即git和docker registry的登录用户名和密码

pipeline {
    agent any
	parameters {
        string defaultValue: 'main', description: '', name: 'Branch', trim: true
    }
    stages {
        stage('拉取代码'){
            steps {
              checkout([$class: 'GitSCM', branches: [[name: "${params.Branch}"]], userRemoteConfigs: [[credentialsId: "${git_auth}", url: "${git_address}"]]])
            }
        }

        stage('代码编译'){
           steps {
             sh """
                JAVA_HOME=/usr/local/jdk
                PATH=$JAVA_HOME/bin:/usr/local/maven/bin:$PATH
                mvn clean package -Dmaven.test.skip=true
                """ 
           }
        }

        stage('构建镜像'){
           steps {
                withCredentials([usernamePassword(credentialsId: "${docker_registry_auth}", passwordVariable: 'password', usernameVariable: 'username')]) {
                sh """
                  echo '
                    FROM tomcat:8.5.43
                    LABEL maitainer lizhenliang
                    RUN rm -rf /usr/local/tomcat/webapps/*
                    ADD target/*.war /usr/local/tomcat/webapps/ROOT.war
                  ' > Dockerfile
                  docker build -t ${image_name} .
                  docker login -u ${username} -p '${password}' ${registry}
                  docker push ${image_name}
                """
                }
           } 
        }

        stage('部署到Docker'){
           steps {
              sh """
              docker rm -f tomcat-java-demo |true
              docker container run -d --name tomcat-java-demo -p 88:8080 ${image_name}
              """
            }
        }
    }
}